package top.vanchor.flexible.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import top.vanchor.flexible.entity.BackAdmin;
import top.vanchor.flexible.mapper.BackAdminMapper;
import top.vanchor.flexible.service.IBackAdminService;
import org.springframework.stereotype.Service;
import top.vanchor.flexible.service.IBackAuthGroupService;
import top.vanchor.flexible.utils.ImageAddress;
import top.vanchor.flexible.utils.JWTUtils;
import top.vanchor.flexible.utils.MD5Encoder;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-01-27
 */
@Log4j2
@Service
public class BackAdminServiceImpl extends ServiceImpl<BackAdminMapper, BackAdmin> implements IBackAdminService {

    @Resource
    private BackAdminMapper mapper;

    @Resource
    private IBackAuthGroupService groupService;

    @Override
    public BackAdmin toLogin(String username, String password) {
        QueryWrapper<BackAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("a_username", username);
        wrapper.eq("a_password", MD5Encoder.encode(password));
        return mapper.selectOne(wrapper);
    }

    @Override
    public IPage<BackAdmin> getList(Integer pageNo, Integer pageSize, String title) {
        IPage<BackAdmin> list = mapper.getList(new Page<>(pageNo, pageSize), title);
        list.getRecords().forEach(it -> {
            it.setAvatarUrl(ImageAddress.getAllPath(it.getAvatarUrl()));
        });
        return list;
    }

    @Override
    public int doEdit(BackAdmin bean) {
        bean.setAUpdateTime(new Date());
        if (bean.getAId() == null) {
            //添加
            bean.setAPassword(MD5Encoder.encode(bean.getAUsername() + "123456"));
            bean.setARealName(bean.getAUsername());
            bean.setAStatus(1);
            bean.setALoginNum(0L);
            bean.setACreateTime(new Date());
            return mapper.insert(bean);
        } else {
            //编辑
            bean.setACreateTime(null);
            QueryWrapper<BackAdmin> wrapper = new QueryWrapper<>();
            wrapper.eq("a_id", bean.getAId());
            return mapper.update(bean, wrapper) + 1;
        }
    }

    @Override
    public int getByUsername(String aUsername) {
        //编辑
        QueryWrapper<BackAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("a_username", aUsername);
        return mapper.selectCount(wrapper);
    }

    @Override
    public int doDeleteBy(List<Integer> ids) {
        QueryWrapper<BackAdmin> wrapper = new QueryWrapper<>();
        wrapper.in("a_id", ids);
        int ret = mapper.delete(wrapper);
        if (ret > 0) {
            log.info("管理员{}（ID为{}）：删除了{}个管理员，id为：{}", JWTUtils.getAuthorName(), JWTUtils.getAuthorId(), ids.size(), ids);
        }
        return ret;
    }

    @Override
    public BackAdmin getAdminUserById(Integer id) {
        BackAdmin admin = mapper.getAdminUserById(id);
        admin.setAvatarUrl(ImageAddress.getAllPath(admin.getAvatarUrl()));
        return admin;
    }

    @Override
    public void updateLoginData(BackAdmin admin) {
        admin.setALoginNum(admin.getALoginNum() + 1);
        admin.setALastTime(new Date());
        try {
            admin.setALastIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        baseMapper.update(admin, new QueryWrapper<BackAdmin>() {{
            eq("a_id", admin.getAId());
        }});
    }

    @Override
    public void deleteUserByGroupIds(List<Integer> ids) {
        baseMapper.delete(new QueryWrapper<BackAdmin>() {{
            in("a_group_id", ids);
        }});
    }
}
